package com.daolion.base;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.daolion.base.anotation.BsActivityAnnotation;

import de.greenrobot.event.EventBus;

/*
    ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ 
       Author   :  lixiaodaoaaa
       Date     :  2020-03-09
       Time     :  10:11
    ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
 */
public class BsActivity extends AppCompatActivity {

    private final static int LAYOUT_ID_INVALID = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        preOnCreate();
        super.onCreate(savedInstanceState);
        if (isNeedEventBus()) {
            EventBus.getDefault().register(this);
        }
        if (getLayoutId() != LAYOUT_ID_INVALID) {
            setContentView(getLayoutId());
        }
    }


    protected void addFragment(int fragmentId, Fragment fragment) {
        getFragmentManager().beginTransaction().add(fragmentId, fragment, null).commit();
    }

    protected void preOnCreate() {
    }

    private BsActivityAnnotation getActivityAnnotation() {
        return getClass().getAnnotation(BsActivityAnnotation.class);
    }


    private int getLayoutId() {
        if (isAnnotationPresent()) {
            return getActivityAnnotation().layoutId();
        }
        return LAYOUT_ID_INVALID;
    }

    private boolean isAnnotationPresent() {
        return getClass().isAnnotationPresent(BsActivityAnnotation.class);
    }

    private boolean isNeedEventBus() {
        if (isAnnotationPresent()) {
            return getActivityAnnotation().isNeedEventBus();
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isNeedEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
